﻿using System;
using System.Collections.Generic;
using System.Text;

namespace CodeGen.TS.Input
{


    public class ParameterParser
    {

        string[] CmdArgs;

        public ParameterParser(string[] cmdArgs = null)
        {
            if (cmdArgs == null)
            {
                cmdArgs = Environment.GetCommandLineArgs();
            }
            this.CmdArgs = cmdArgs;
        }
        public string ParseArgumentValue(string argument)
        {
            string value = "";
            bool isAtParsing = false;
            bool hasValue = false;
            foreach (string arg in this.CmdArgs)
            {
                if (isAtParsing)
                {
                    if (value == "" && !arg.StartsWith("\""))
                    {
                        return arg;
                    }
                    else
                    {
                        if (value != "")
                            value += " ";
                        value += arg;
                        if (arg.EndsWith("\""))
                        {
                            isAtParsing = false;
                            break;
                        }
                    }
                }
                else
                {
                    if (arg.Equals("/" + argument, StringComparison.CurrentCultureIgnoreCase))
                    {
                        hasValue = true;
                        isAtParsing = true;
                    }
                    if (arg.Equals("--" + argument, StringComparison.CurrentCultureIgnoreCase))
                    {
                        hasValue = true;
                        isAtParsing = true;
                    }
                }
            }
            if (!hasValue)
                return null;
            value = value.Trim();//Spaces at start and at end are not allowed
            value = value.Replace("\"", "");//" is an invalid char
            return value;
        }

        public bool ContainsArgument(string argument)
        {
            foreach (string arg in this.CmdArgs)
            {
                if (arg.Equals("/" + argument, StringComparison.CurrentCultureIgnoreCase))
                    return true;
                if (arg.Equals("--" + argument, StringComparison.CurrentCultureIgnoreCase))
                    return true;
            }
            return false;
        }

    }
}
